<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author FIRE
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'wms:pu:rd01:wmsRd01:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #childList>
        <BasicTable
          @register="registerWmsRds01Table"
          @row-click="handleWmsRds01RowClick"
        />
        <a-button class="mt-2" @click="handleWmsRds01Add" v-auth="'wms:pu:rd01:wmsRd01:edit'">
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsWmsPuRd01WmsRd01Form">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { WmsRd01, wmsRd01Save, wmsRd01Form } from '/@/api/wms/pu/rd01/wmsRd01';
  import { basInvListData } from '/@/api/bas/inv/basInv';
import select from '/@/views/test/testData/select';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('wms/pu.rd01.wmsRd01');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<WmsRd01>({} as WmsRd01);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增采购入库单') : t('编辑采购入库单'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('入库单号'),
      field: 'djno',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      rules: [{ required: true }, { pattern: /^[a-zA-Z0-9_]*$/, message: t('请输入字母数字下划线') }],
    },
    {
      label: t('采购单号'),
      field: 'poCode',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      rules: [{ required: true }, { pattern: /^[a-zA-Z0-9_]*$/, message: t('请输入字母数字下划线') }],
    },
    {
      label: t('u8单号'),
      field: 'u8Djno',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('供应商编码'),
      field: 'pomain.venCode',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('供应商名称'),
      field: 'pomain.venName',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('入库日期'),
      field: 'ddate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        showTime: false,
      },
    },
    {
      label: t('存货编码'),
      field: 'invCode',
      required: true,
      component: 'Input',
      componentProps: {
        maxlength: 50,
        disabled: true,
      },
    },
    {
      label: t('存货名称'),
      field: 'invCode',
      fieldLabel: 'basInv.invName',
      component: 'ListSelect',
      // componentProps: {
      //   selectType: 'basInvSelect',
        
      // },
      componentProps: ({ tableAction, formModel }) => {
        return {
          selectType: 'basInvSelect',
          onSelect: (values) => {
            formModel['basInv.unitName'] = values[0].unitName;
            formModel['basInv.invStd'] = values[0].invStd;
          }
        }
      },
      required: true,
    },
    {
      label: t('规格型号'),
      field: 'basInv.invStd',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('单位'),
      field: 'basInv.unitName',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('税率'),
      field: 'itaxrate',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
      ifShow: false,
    },
    {
      label: t('汇率'),
      field: 'iexchrate',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
      ifShow: false,
    },
    {
      label: t('仓库'),
      field: 'whCode',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      ifShow: false,
    },
    {
      label: t('采购入库单明细'),
      field: 'childList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'childList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerWmsRds01Table, wmsRds01Table] = useTable({
    actionColumn: {
      width: 30,
      actions: (record: Recordable) => [
        {
          icon: 'i-ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleWmsRds01Delete.bind(this, record),
          },
          auth: 'wms/pu:rd01:wmsRd01:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setWmsRds01TableData(_res: Recordable) {
    wmsRds01Table.setColumns([
      {
        title: t('数量'),
        dataIndex: 'iqty',
        width: 30,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editRule: true,
      },
      {
        title: t('件数'),
        dataIndex: 'inum',
        width: 30,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
      },
      {
        title: t('批次'),
        dataIndex: 'cbatch',
        width: 100,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
        ifShow: (record) => record?.basInv?.binvbatch === '1',
      },
      {
        title: t('货位'),
        dataIndex: 'posCode',
        width: 100,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
        // 判断basInv.binvbatch 为1时显示
        ifShow: (record) => record?.basWare?.bwhpos === '1',

      },
      {
        title: t('原币含税单价'),
        dataIndex: 'ioritaxcost',
        width: 80,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('原币无税单价'),
        dataIndex: 'ioricost',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('取价方式'),
        dataIndex: 'btaxcost',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 10,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('税率'),
        dataIndex: 'itaxrate',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('汇率'),
        dataIndex: 'iexchrate',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('原币无税金额'),
        dataIndex: 'iorimoney',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('原币价税合计'),
        dataIndex: 'iorisum',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('原币税额'),
        dataIndex: 'ioritaxprice',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('备注'),
        dataIndex: 'remarks',
        width: 50,
        align: 'left',
        editRow: true,
        editComponent: 'InputTextArea',
        editComponentProps: {
          maxlength: 500,
        },
        editRule: false,
      },
    ]);
    wmsRds01Table.setTableData(record.value.childList || []);
  }

  function handleWmsRds01RowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleWmsRds01Add() {
    wmsRds01Table.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleWmsRds01Delete(record: Recordable) {
    wmsRds01Table.deleteTableDataRecord(record);
  }

  async function getChildList() {
    let childListValid = true;
    let childList: Recordable[] = [];
    for (const record of wmsRds01Table.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        childListValid = false;
      }
      childList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of wmsRds01Table.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      childList.push({
        ...record,
        status: '1',
      });
    }
    if (!childListValid) {
      throw { errorFields: [{ name: ['childList'] }] };
    }
    return childList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await wmsRd01Form(data);
    record.value = (res.wmsRd01 || {}) as WmsRd01;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setWmsRds01TableData(res);
    updateSchema([
      {
        field: 'djno',
        componentProps: {
          disabled: !record.value.isNewRecord,
        },
      },
    ]);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        djno: record.value.djno,
      };
      data.childList = await getChildList();
      // console.log('submit', params, data, record);
      const res = await wmsRd01Save(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
